package BookManagement.controller;

import BookManagement.domain.*;
import BookManagement.service.BookService;
import BookManagement.service.PurchaseService;
import BookManagement.service.SpendService;
import BookManagement.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/purchase")
public class PurchaseController {
    @Autowired
    @Qualifier("purchaseService")
    private PurchaseService purchaseService;

    @Autowired
    @Qualifier("spendService")
    private SpendService spendService;

    @Autowired
    @Qualifier("userService")
    private UserService userService;

    @Autowired
    @Qualifier("bookService")
    private BookService bookService;

    @RequestMapping("/readPayPhoto")
    public void readPayPhoto(HttpSession hs,HttpServletResponse response){
        try{
            FileInputStream fis=new FileInputStream(hs.getServletContext().getRealPath("/statics/payphoto.png"));
            byte[] d=new byte[fis.available()];
            fis.read(d);
            fis.close();
            response.setContentType("img/*");
            response.setCharacterEncoding("utf-8");
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(d);
            outputStream.flush();
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @RequestMapping("/purchaseBook")
    public ModelAndView purchaseBook(HttpSession hs,String bookISBN){
        ModelAndView mav=new ModelAndView();
        User user =userService.findUserByUsername( (String) hs.getAttribute("usercurrent"));
        if(user==null){
            return new ModelAndView("redirect:/account/toLogin");
        }
        String purMsg=new String();
        Book b = bookService.findByISBN(bookISBN);
        if(b.getBookPrices()>user.getBalance()){
            purMsg="余额不足，请充值！";
            mav.setViewName("/user/purFail");
            return mav;
        }
        else{
            double balance= user.getBalance()-b.getBookPrices();
            user.setBalance(balance);
            user.setPurchaseNum(user.getPurchaseNum()+1);
            String time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis());
            Spend spend=new Spend(user.getUserName(),"支出",time,"-"+String.valueOf(b.getBookPrices()),balance);
            Purchase purchase=new Purchase(b.getBookISBN(),user.getUserName(),time,String.valueOf(b.getBookPrices()),b.getBookName(),b.getAuthor());
            spendService.newspend(spend);
            purchaseService.purchase(purchase);
            userService.updateUser(user);
            purMsg="购买成功！";
            mav.setViewName("/user/purSuccessfully");
            return mav;
        }
    }

    @RequestMapping("/showPurchaseByUser")
    public ModelAndView showPurchaseByUser(HttpSession hs,String pageNo){
        ModelAndView mav=new ModelAndView();
        User user =userService.findUserByUsername( (String) hs.getAttribute("usercurrent"));
        if(user==null){
            return new ModelAndView("redirect:/account/toLogin");
        }
        Page p=new Page(pageNo,10,purchaseService.findPurchaseCountByUser(user.getUserName()));
        HashMap<String,Object>map=new HashMap<>();
        map.put("start",p.getStart());
        map.put("size",p.getPageSize());
        map.put("username",user.getUserName());
        List<Purchase> purchaseList = purchaseService.findAllPurchaseByUser(map);
        mav.addObject("purchaseList",purchaseList);
        mav.addObject("username",user.getName());
        mav.addObject("page",p);
        mav.setViewName("/user/allPurchasingOfUser");
        return mav;
    }

    @RequestMapping("/showPurchaseByBook")
    public ModelAndView showPurchaseByBook(HttpSession hs,String pageNo,String bookISBN){
        ModelAndView mav=new ModelAndView();
        User user =userService.findUserByUsername( (String) hs.getAttribute("usercurrent"));
        if(user==null){
            return new ModelAndView("redirect:/account/toLogin");
        }
        Page p=new Page(pageNo,10,purchaseService.findPurchaseCountByBook(bookISBN));
        HashMap<String,Object>map=new HashMap<>();
        map.put("start",p.getStart());
        map.put("size",p.getPageSize());
        map.put("bookISBN",bookISBN);
        Book b=bookService.findByISBN(bookISBN);
        List<Purchase> purchaseList = purchaseService.findAllPurchaseByBook(map);
        mav.addObject("purchaseList",purchaseList);
        mav.addObject("bookName",b.getBookName());
        mav.addObject("page",p);
        mav.setViewName("admin/books/allPurchasingOfBook");
        return mav;
    }


    @RequestMapping("/prepaidBalance")
    public void prepaidBalance(double money,HttpSession hs){
        User user =userService.findUserByUsername( (String) hs.getAttribute("usercurrent"));
        String time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis());
        double balance=user.getBalance();
        balance+=money;
        user.setBalance(balance);
        Spend spend=new Spend(user.getUserName(),"充值",time,"+"+String.valueOf(money),balance);
        spendService.newspend(spend);
        userService.updateUser(user);
        hs.setAttribute("balance",user.getBalance());
    }

    @RequestMapping("/paySuccessfully")
    public ModelAndView paySuccessfully(HttpSession hs) throws InterruptedException {
        User user =userService.findUserByUsername( (String) hs.getAttribute("usercurrent"));
        if(user==null){
            return new ModelAndView("redirect:/account/toLogin");
        }
        Thread.currentThread().sleep(1000);
        return new ModelAndView("/user/paySuccessfully");
    }
}
